import json
import paddlehub as hub
import cv2
import pymysql
import torch
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
import os

def car_recognition(request):
    return render(request, 'carRecognition.html')

def license_plate_recognition(request):

    if request.method == 'POST':
        uploaded_file = request.FILES.get('imageUpload')

        if not uploaded_file:
            return JsonResponse({'code': 500, 'message': '未上传图片！', 'data': None}, status=500)

        image_name = uploaded_file.name
        print(f"Uploaded file: {uploaded_file.name}")

        # 保存文件
        image_path = os.path.join('static', 'images', image_name)
        with open(image_path, 'wb') as f:
            for chunk in uploaded_file.chunks():
                f.write(chunk)

        try:
            # 加载模型
            model = torch.hub.load("ultralytics/yolov5", "custom", path="./weights/best.pt")
            res = model(image_path)
            data = res.pandas().xyxy[0].to_dict(orient="records")

            if not data:
                return JsonResponse({'code': 500, 'message': '未检测到车牌！', 'data': None}, status=500)

            ds = data[0]
            img = cv2.imread(image_path)

            # 裁剪图片
            cropped_img = img[int(ds['ymin']):int(ds['ymax']), int(ds['xmin']):int(ds['xmax'])]
            cropped_image_path = os.path.join('static', 'result_images', image_name)
            cv2.imwrite(cropped_image_path, cropped_img)

            # OCR 识别
            ocr = hub.Module(name="chinese_ocr_db_crnn_server")
            result = ocr.recognize_text(images=[cv2.imread(cropped_image_path)])

            if result and result[0] and 'data' in result[0]:
                license_plate = result[0]['data'][0]['text']
                print(f"Detected License Plate: {license_plate}")

                # 查询数据库
                household_info = queryHouseholdByLicensePlate(license_plate)
                # 构建响应数据
                response_data = {
                    'code': 200,
                    'message': '识别成功',
                    'data': {
                        'license_plate': license_plate,
                        'household_info': household_info if household_info else None,
                    }
                }
                return JsonResponse(response_data)
            else:
                return JsonResponse({'code': 500, 'message': 'OCR识别失败！', 'data': None}, status=500)

        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'code': 500, 'message': '处理过程中发生错误！', 'data': None}, status=500)

    else:
        return JsonResponse({'code': 500, 'message': '请求方法不支持！', 'data': None}, status=500)

def queryHouseholdByLicensePlate(license_plate):
    # 连接数据库
    con = pymysql.Connect(
        host="localhost",
        user="root",
        passwd="root",
        database="property_management_system",
        charset="utf8"
    )
    cursor = con.cursor()
    sql = 'select * from householders where car_license_plate = %s'
    cursor.execute(sql, (license_plate,))
    result = cursor.fetchone()
    cursor.close()
    con.close()
    return result